package com.example.waimai.contraller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.waimai.common.BaseContext;
import com.example.waimai.common.R;
import com.example.waimai.pojo.ShoppingCart;
import com.example.waimai.service.ServiceShoppingCart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartCOuntroller {
    @Autowired
    private ServiceShoppingCart serviceShoppingCart;


    @PostMapping("/add")//购物车添加功能
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){

        //查询用户id
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);

        Long dishId = shoppingCart.getDishId();

        //判断菜品or套餐是否在购物车里
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,currentId);
        if(dishId!=null){
            lqw.eq(ShoppingCart::getDishId,dishId);
        }else{
            lqw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart one = serviceShoppingCart.getOne(lqw);

        //在 则数量+1
        //else 加入购物车 默认值为1
        if(one!=null){
            Integer number = one.getNumber();
            one.setNumber(number+1);
            serviceShoppingCart.updateById(one);
        }else{
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            serviceShoppingCart.save(shoppingCart);
            one=shoppingCart;
        }
        return R.success(one);
    }

    @GetMapping("/list")//查看购物车
    public R<List<ShoppingCart>> list(){
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        lqw.orderByDesc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = serviceShoppingCart.list(lqw);
        return R.success(list);
    }

    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());
        serviceShoppingCart.remove(lqw);
        return R.success("清空购物车");
    }
}
